
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using System;
using System.Runtime.Serialization;

public class SystemExceptionAdapter : CrossBindingAdaptor
{
    public override Type BaseCLRType
    {
        get
        {
            return typeof(System.SystemException);//这是你想继承的那个类
        }
    }
    public override Type AdaptorType
    {
        get
        {
            return typeof(Adaptor);//这是实际的适配器类
        }
    }
    public override object CreateCLRInstance(ILRuntime.Runtime.Enviorment.AppDomain appdomain, ILTypeInstance instance)
    {
        return new Adaptor(appdomain, instance);//创建一个新的实例
    }
    //实际的适配器类需要继承你想继承的那个类，并且实现CrossBindingAdaptorType接口
    public class Adaptor : System.SystemException, CrossBindingAdaptorType
    {
        ILTypeInstance instance;
        ILRuntime.Runtime.Enviorment.AppDomain appdomain;
        //缓存这个数组来避免调用时的GC Alloc
        object[] param1 = new object[1];
        private IMethod iSystemExceptionCtor;

        public ILTypeInstance ILTypeInstance
        {
            get { return instance; }
        }

        public ILTypeInstance ILInstance { get { return instance; } }

        public Adaptor()
        {

        }

        public Adaptor(ILRuntime.Runtime.Enviorment.AppDomain appdomain, ILTypeInstance instance)
        {
            this.appdomain = appdomain;
            this.instance = instance;
        }


        public Adaptor(SerializationInfo info, StreamingContext context)
        {
            if (this.iSystemExceptionCtor == null)
            {
                this.iSystemExceptionCtor = instance.Type.GetConstructor(2);        //两个参数
            }
            this.appdomain.Invoke(this.iSystemExceptionCtor, instance);
        }
        

        public override string ToString()
        {
            IMethod m = this.appdomain.ObjectType.GetMethod("ToString", 0);
            m = instance.Type.GetVirtualMethod(m);
            if (m == null || m is ILMethod)
            {
                return instance.ToString();
            }
            return instance.Type.FullName;
        }
    }
}